package com.hxzy.controller.admin.login;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.hxzy.common.resp.R;
import com.hxzy.controller.admin.login.req.AdminLoginReq;
import com.hxzy.entity.Employee;
import com.hxzy.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "后台-登录Api")
@RestController
@RequestMapping(value = "/api")
public class AdminLoginController {

    /**
     * 注入员工表
     */
    @Autowired
    private EmployeeService  employeeService;

    /**
     * 登录模型
     * @param req
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody @Valid AdminLoginReq req){
        Employee  employee=this.employeeService.login(req);

        //使用sa-token，来生成令牌
        //https://sa-token.cc/doc.html#/plugin/jwt-extend
        SaLoginModel saLoginModel = new SaLoginModel();
        saLoginModel.setExtra("username",employee.getLoginName());
        saLoginModel.setExtra("gender",employee.getGender());
        saLoginModel.setExtra("avatar",employee.getAvatar());
        saLoginModel.setExtra("root",employee.getRoot());
        saLoginModel.setExtra("permissions", "admin");

        //换令牌，它会自动帮你存储redis中
        StpUtil.login(employee.getId(), saLoginModel);

        //获取令牌
        String token=StpUtil.getTokenInfo().tokenValue;

        return R.success(token);
    }


    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @SaCheckLogin
    @GetMapping(value = "/user/info")
    public R   getUserInfo(){
        Map<String,Object> dataMap=new HashMap<>();
        dataMap.put("name", StpUtil.getExtra("username"));
        dataMap.put("gender", StpUtil.getExtra("gender"));
        dataMap.put("avatar", StpUtil.getExtra("avatar"));
        dataMap.put("root", StpUtil.getExtra("root"));
        dataMap.put("permissions",  StpUtil.getExtra("permissions"));

        //自定义Map   https://doc.hutool.cn/pages/SymmetricCrypto/#desede%E5%AE%9E%E7%8E%B0
        //Map转换成  json字符串
        //使用 对称加密算法   进行加密
        //把加密字符串放到  dataMap.put("userinfo", 加密值);

        //主键
        dataMap.put("id",StpUtil.getLoginIdAsLong());
        return R.success(dataMap);
    }

    /**
     * 退出
     * @return
     */
    @ApiOperation(value = "退出登录")
    @SaCheckLogin
    @PostMapping(value = "/logout")
    public R logout(){
        StpUtil.logout();
        return R.success();
    }


}
